import 'dart:async';

import 'package:flutter/material.dart';

class BlocDemo extends StatelessWidget {
  const BlocDemo({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final PageBloc pageBloc = PageBloc();
    return StreamBuilder(
      stream: pageBloc.stream,
      initialData: 0,
      builder: (context, snapShot) {
        return Scaffold(
          appBar: AppBar(
            title: Text('BlocDemo'),
            elevation: 0.0,
            centerTitle: true,
          ),
          backgroundColor: Colors.white,
          body: Center(child: Text(snapShot.data.toString())),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              pageBloc.add();
            },
            child: Icon(Icons.add),
          ),
        );
      },
    );
  }
}

class PageBloc {
  int count = 0;
  StreamController<int> _streamCtr = StreamController<int>();
  //对外提供入口
  StreamSink<int> get _countSink => _streamCtr.sink;
  //提供stream StreamBuilder订阅
  Stream<int> get stream => _streamCtr.stream;

  void dispose() {
    _streamCtr.close();
  }

  void add() {
    count++;
    _countSink.add(count);
  }
}
